package club.calong.sanniu.pojo.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.tomcat.util.buf.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

// 数据库中该字段存储的类型
@MappedJdbcTypes(JdbcType.VARCHAR)
// 需要转换的对象
@MappedTypes(Set.class)
public class IntegerSetConverter extends BaseTypeHandler<Set<Integer>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Set<Integer> integers, JdbcType jdbcType) throws SQLException {

        List<String> result = new ArrayList<>(integers.size());
        integers.forEach(item -> {
            result.add(item.toString());
        });
        preparedStatement.setString(i, StringUtils.join(result, ','));
    }

    @Override
    public Set<Integer> getNullableResult(ResultSet resultSet, String s) throws SQLException {

        if (resultSet.getString(s) == null)
            return null;
        else {
            List<String> list = Arrays.asList(resultSet.getString(s).split(","));
            HashSet<Integer> result = new HashSet<>(list.size());
            list.forEach(item -> {
                result.add(Integer.parseInt(item));
            });
            return result;
        }
    }

    @Override
    public Set<Integer> getNullableResult(ResultSet resultSet, int i) throws SQLException {

        if (resultSet.getString(i) == null)
            return null;
        else {
            List<String> list = Arrays.asList(resultSet.getString(i).split(","));
            HashSet<Integer> result = new HashSet<>(list.size());
            list.forEach(item -> {
                result.add(Integer.parseInt(item));
            });
            return result;
        }
    }

    @Override
    public Set<Integer> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {

        if (callableStatement.getString(i) == null)
            return null;
        else {
            List<String> list = Arrays.asList(callableStatement.getString(i).split(","));
            HashSet<Integer> result = new HashSet<>(list.size());
            list.forEach(item -> {
                result.add(Integer.parseInt(item));
            });
            return result;
        }
    }
}
